package org.nestor.demo.service;

import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import org.nestor.demo.protobuf.Buyer;
import org.nestor.demo.protobuf.Order;
import org.nestor.demo.protobuf.OrderQueryClientStreamGrpc;
import org.nestor.demo.protobuf.OrderQueryGrpc;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Nestor.Bian
 * @version : V 1.0
 * @date : 2025/3/6
 */
public class OrderQueryClientStreamServiceImpl extends OrderQueryClientStreamGrpc.OrderQueryClientStreamImplBase {

    /**
     * 客户端流式与双向流式不一样，只能返回单个值，双向流可以返回多值
     *
     * @param responseObserver
     * @return io.grpc.stub.StreamObserver<org.nestor.demo.protobuf.Buyer>
     * @date : 2025/4/26 22:41
     * @author : Nestor.Bian
     * @since : 1.0
     */
    @Override
    public StreamObserver<Buyer> listOrders(StreamObserver<Order> responseObserver) {
        return new StreamObserver<Buyer>() {
            @Override
            public void onNext(Buyer value) {
                System.out.println("Buyer value = " + value);
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("客户端参数发送完成");
                // 只能结束时发送单个响应结果，onNext只能调用一次
                responseObserver.onNext(Order.newBuilder()
                        .setOrderId(1)
                        .setProductId(1001)
                        .setOrderTime(System.currentTimeMillis()/1000)
                        .setBuyerRemark(("remark-1"))
                        .build());
                responseObserver.onCompleted();
            }
        };
    }
}
